﻿/// <reference path="tap.js" />
/// <reference path="../jquery-1.8.2.js" />

function GridHelper(name) {
    var me = this;
    this.baseName = name;
    this.autoResizeHeaderOffset = 235;
    this.gridId = name + "Grid";
    this.pagerId = name + "Pager";
    this.$gridElement = null;
    this.$pagerElement = null;
    this.$editDialogElement = null;
    this.editorFunctionName = name + "LaunchEditor";
    this.editorFunction = null;
    this.deleteFunctionName = name + "DeleteRecord";
    this.deleteFunction = null;
    this.customLoadCompleteFunctionName = name + "LoadComplete";
    this.customLoadCompleteFunction = null;
    this.customGridCompleteFunctionName = name + "GridComplete";
    this.customGridCompleteFunction = null;
    this.customLoadErrorFunctionName = name + "LoadError";
    this.customLoadErrorFunction = null;
    this.dataSourceDataType = null;
    this.minimumHeight = 150;

    this.loadError = function (xhr, status, error) {
        /*
         [AllowAnonymous]
        [HttpPost]
        public JsonResult ReportAjaxError(string s, string e, string x)
        {
            var result = new { Success = true };
            Logger.Log(new TAPException(TAPErrorCode.AjaxError, e, new Dictionary<string, object> { 
                { "AdditionalContext", new { Info=x, UserAgent = Request.UserAgent, UrlReferrer = Request.UrlReferrer } } 
            }));
            return Json(result);
        }
        */
        //Feedback/ReportAjaxError

        var $e = $("#" + me.gridId);
        reportAjaxError(status, error, "baseName=" + me.baseName + "\r\npostData=" + serializeObject($e.jqGrid('getGridParam', 'postData')));

        if ((me.customLoadErrorFunction == null) && (me.customLoadErrorFunctionName != null) && (eval("typeof " + me.customLoadErrorFunctionName + " == 'function'")))
            me.customLoadErrorFunction = eval(me.customLoadErrorFunctionName);
        if (me.customLoadErrorFunction != null) me.customLoadErrorFunction(me, xhr, status, error);

        alert("Server Error - This error has been reported. Please try again.");
    };

    this.loadComplete = function () {
        var $e = $("#" + me.gridId);
        if ($e.length == 1) me.$gridElement = $e;
        else {
            //TODO: Make a better error here...
            alert("Grid not found error (#" + me.gridId + ")!");
        }

        $e = $("#" + me.pagerId);
        if ($e.length == 1) me.$pagerElement = $e;

        if ((me.editorFunction == null) && (me.editorFunctionName != null) && (eval("typeof " + me.editorFunctionName + " == 'function'")))
            me.editorFunction = eval(me.editorFunctionName);
        me.$gridElement.find(".grid-edit-icon").click(me.editButtonClick);

        if ((me.deleteFunction == null) && (me.deleteFunctionName != null) && (eval("typeof " + me.deleteFunctionName + " == 'function'")))
            me.deleteFunction = eval(me.deleteFunctionName);
        me.$gridElement.find(".grid-delete-icon").click(me.deleteButtonClick);

        if ((me.customLoadCompleteFunction == null) && (me.customLoadCompleteFunctionName != null) && (eval("typeof " + me.customLoadCompleteFunctionName + " == 'function'")))
            me.customLoadCompleteFunction = eval(me.customLoadCompleteFunctionName);
        if (me.customLoadCompleteFunction != null) me.customLoadCompleteFunction(me);

        if ((me.customGridCompleteFunction == null) && (me.customGridCompleteFunctionName != null) && (eval("typeof " + me.customGridCompleteFunctionName + " == 'function'")))
            me.customGridCompleteFunction = eval(me.customGridCompleteFunctionName);
        if (me.customGridCompleteFunction != null) me.customGridCompleteFunction(me);

        $(window).bind('resize', me.fitGridToPage);
    };

    this.gridComplete = function () {
        if ((me.customGridCompleteFunction == null) && (me.customGridCompleteFunctionName != null) && (eval("typeof " + me.customGridCompleteFunctionName + " == 'function'")))
            me.customGridCompleteFunction = eval(me.customGridCompleteFunctionName);
        if (me.customGridCompleteFunction != null) me.customGridCompleteFunction(me);
    };

    this.doubleClickRow = function (rowid, iRow, iCol, e) {
        me.editRow(rowid);
    };

    this.fitGridToPage = function () {
        me.$gridElement.setGridHeight(me.getEstimatedGridHeight());
    };

    this.getEstimatedGridHeight = function () {
        var height = $(window).height() - me.autoResizeHeaderOffset;
        if (height < me.minimumHeight) height = me.minimumHeight;
        return height;
    };

    this.reload = function () {
        me.$gridElement.trigger("reloadGrid");
    };

    this.getRowIdFromElement = function (elem) {
        var $tr = $(elem).closest("tr");
        if ($tr.length > 0) {
            var rowId = $tr.get(0).id;
            if (rowId) {
                //var rowData = me.$gridElement.jqGrid('getRowData', rowId);
                return rowId;
            }
        }
        return null;
    };

    this.editButtonClick = function (e) {
        me.editRow(me.getRowIdFromElement(this));
    };

    this.editRow = function (rowId) {
        if (rowId != null) {
            var rowData = me.$gridElement.jqGrid('getRowData', rowId);
            if (me.editorFunction != null) me.editorFunction(rowId, rowData);
        }
        else {
            //TODO: Make a better error here...
            alert("Edit error!");
        }
    };

    this.deleteButtonClick = function (e) {
        var rowId = me.getRowIdFromElement(this);
        if (rowId != null) {
            var rowData = me.$gridElement.jqGrid('getRowData', rowId);
            if (me.deleteFunction != null) me.deleteFunction(rowId, rowData);
        }
        else {
            //TODO: Make a better error here...
            alert("delete error!");
        }
    };
}

$.extend($.fn.fmatter, {
    editImageFormatter: function (cellvalue, options, rowdata) {
        if (cellvalue == null) cellvalue = "";
        var html = "<img src=\"" + TapUrls.EditIcon + "\" border=\"0\" title=\"Edit\" class=\"grid-edit-icon\"/>";
        html += "<input type=\"hidden\" value=\"" + cellvalue + "\" id=\"" + options.rowId + "_" + options.colModel.name + "\"/>";
        return html;
    }
});

$.extend($.fn.fmatter.editImageFormatter, {
    unformat: function (cellvalue, options, cellobject) {
        return $(cellobject).Find("input").val();
    }
});

$.extend($.fn.fmatter, {
    editDeleteImageFormatter: function (cellvalue, options, rowdata) {
        if (cellvalue == null) cellvalue = "";
        var html = "<img src=\"" + TapUrls.EditIcon + "\" border=\"0\" title=\"Edit\" class=\"grid-edit-icon\"/> ";
        html += "<img src=\"" + TapUrls.DeleteIcon + "\" border=\"0\" title=\"Delete\" class=\"grid-delete-icon\"/>";
        html += "<input type=\"hidden\" value=\"" + cellvalue + "\" id=\"" + options.rowId + "_" + options.colModel.name + "\"/>";
        return html;
    }
});

$.extend($.fn.fmatter.editDeleteImageFormatter, {
    unformat: function (cellvalue, options, cellobject) {
        return $(cellobject).Find("input").val();
    }
});

$.extend($.fn.fmatter, {
    checkBoxFormatter: function (cellvalue, options, rowdata) {
        var isChecked = cellvalue != null && cellvalue != "";
        if (isChecked && typeof (cellvalue) == "boolean") isChecked = cellvalue;
        else if (isChecked) isChecked = 'tTyY1'.indexOf((cellvalue + '').charAt(0)) >= 0;
        return "<input type=\"checkbox\" readonly=\"true\"" + (isChecked ? " checked=\"true\"" : "") + "/>";
    }
});

$.extend($.fn.fmatter.checkBoxFormatter, {
    unformat: function (cellvalue, options, cellobject) {
        var htmlVal = jQuery(cellobject).html();
        var isChecked = htmlVal.indexOf("checked") >= 0;
        return isChecked + '';
    }
});

$.extend($.fn.fmatter, {
    checkImageFormatter: function (cellvalue, options, rowdata) {
        var html = "";
        if (cellvalue == true) {
            html += "<img src=\"" + TapUrls.CheckIcon + "\" border=\"0\" class=\"gridCheckIcon\"/>";
        }
        else {
            html += "&nbsp;";
        }
        html += "<input type=\"hidden\" value=\"" + cellvalue + "\" id=\"" + options.rowId + "_" + options.colModel.name + "\"/>";

        return html;
    }
});

$.extend($.fn.fmatter.checkImageFormatter, {
    unformat: function (cellvalue, options, cellobject) {
        var isChecked = $(cellobject).Find("input").val() == "true";
        return isChecked;
    }
});

$.extend($.fn.fmatter, {
    dateYyyymmddFormatter: function (cellvalue, options, rowdata) {
        var html = "";
        if (cellvalue != null && cellvalue != "") {
            var date = parseDateString(cellvalue);
            html += $.format.date(date, 'yyyy/MM/dd');
        }
        else {
            html += "&nbsp;";
        }
        html += "<input type=\"hidden\" value=\"" + cellvalue + "\" id=\"" + options.rowId + "_" + options.colModel.name + "\"/>";

        return html;
    }
});

$.extend($.fn.fmatter.dateYyyymmddFormatter, {
    unformat: function (cellvalue, options, cellobject) {
        return $(cellobject).Find("input").val();
    }
});
